package proxy4jdbc3.jdbc;

import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.StringTokenizer;

/**
 * Wraps a PreparedStatement and reports method calls.
 */
public class PreparedStatementProxy extends StatementProxy implements
		PreparedStatement {

	/**
	 * holds list of bind variables for tracing
	 */
	@SuppressWarnings("unchecked")
	protected final List argTrace = new ArrayList();

	/**
	 * The real PreparedStatement that this PreparedStatementProxy wraps.
	 */
	protected PreparedStatement realPreparedStatement;


	private String sql;
		
	/**
	 * Create a prepared statement for reports activity of proxified realPreparedStatement 
	 * @param sql
	 *            SQL for the prepared statement that is being spied upon.
	 * @param connectionProxy
	 *            ConnectionProxy that was called to produce this
	 *            PreparedStatement.
	 * @param realPreparedStatement
	 *            The actual PreparedStatement that is being spied upon.
	 */
	public PreparedStatementProxy(String sql, ConnectionProxy connectionProxy,
			PreparedStatement realPreparedStatement) {
		super(connectionProxy, realPreparedStatement);
		this.sql = sql;
		this.realPreparedStatement = realPreparedStatement;
	}
	
	@Override
	public PreparedStatement getProxyfied() {		
		return realPreparedStatement;
	}

	/**
	 * Store an argument (bind variable) into the argTrace list (above) for
	 * later dumping.
	 * 
	 * @param i
	 *            index of argument being set.
	 * @param typeHelper
	 *            optional additional info about the type that is being set in
	 *            the arg
	 * @param arg
	 *            argument being bound.
	 */
	protected void argTraceSet(int i, Object arg) {
		i--; // make the index 0 based
		synchronized (argTrace) {
			// if an object is being inserted out of sequence, fill up missing
			// values with null...
			while (i >= argTrace.size()) {
				argTrace.add(argTrace.size(), null);
			}
			if (arg != null) {
				argTrace.set(i, arg.toString());
			} else {
				argTrace.set(i, "null");
			}
		}
	}

	protected String dumpedSql() {
		StringBuffer dumpSql = new StringBuffer();
		int lastPos = 0;
		int Qpos = sql.indexOf('?', lastPos); // find position of first
		// question mark
		int argIdx = 0;
		String arg;

		while (Qpos != -1) {
			// get stored argument
			synchronized (argTrace) {
				try {
					arg = (String) argTrace.get(argIdx);
				} catch (IndexOutOfBoundsException e) {
					arg = "?";
				}
			}
			if (arg == null) {
				arg = "?";
			}

			argIdx++;

			dumpSql.append(sql.substring(lastPos, Qpos)); // dump segment of
			// sql up to
			// question mark.
			lastPos = Qpos + 1;
			Qpos = sql.indexOf('?', lastPos);
			dumpSql.append(arg);
		}
		if (lastPos < sql.length()) {
			dumpSql.append(sql.substring(lastPos, sql.length())); // dump last
			// segment
		}

		// insert line breaks into sql to make it more readable
		StringBuffer output = new StringBuffer();
		StringTokenizer st = new StringTokenizer(dumpSql.toString());

		String token;
		int linelength = 0;

		while (st.hasMoreElements()) {
			token = (String) st.nextElement();

			output.append(token);
			linelength += token.length();
			output.append(" ");
			linelength++;
			if (linelength > 90) {
				output.append("\n");
				linelength = 0;
			}
		}

		return output.toString();
	}

	


	// forwarding methods

	public void setTime(int parameterIndex, Time x) throws SQLException {
		argTraceSet(parameterIndex, x);
		getProxyfied().setTime(parameterIndex, x);
	}

	public void setTime(int parameterIndex, Time x, Calendar cal)
			throws SQLException {
		argTraceSet(parameterIndex, x);
		getProxyfied().setTime(parameterIndex, x, cal);
	}

	public void setCharacterStream(int parameterIndex, Reader reader, int length)
			throws SQLException {
		argTraceSet(parameterIndex, "<Reader of length " + length + ">");
		realPreparedStatement
				.setCharacterStream(parameterIndex, reader, length);
	}

	public void setNull(int parameterIndex, int sqlType) throws SQLException {
		argTraceSet(parameterIndex, "null");
		getProxyfied().setNull(parameterIndex, sqlType);
	}

	public void setNull(int paramIndex, int sqlType, String typeName)
			throws SQLException {
		argTraceSet(paramIndex, null);
		getProxyfied().setNull(paramIndex, sqlType, typeName);
	}

	public void setRef(int i, Ref x) throws SQLException {
		argTraceSet(i, x);
		getProxyfied().setRef(i, x);
	}

	public void setBoolean(int parameterIndex, boolean x) throws SQLException {
		argTraceSet(parameterIndex, Boolean.toString(x));
		getProxyfied().setBoolean(parameterIndex, x);
	}

	public void setBlob(int i, Blob x) throws SQLException {
		argTraceSet(i, "<Blob of size " + x.length() + ">");
		getProxyfied().setBlob(i, x);
	}

	public void setClob(int i, Clob x) throws SQLException {
		argTraceSet(i, "<Clob of size " + x.length() + ">");
		getProxyfied().setClob(i, x);
	}

	public void setArray(int i, Array x) throws SQLException {
		argTraceSet(i, x);
		getProxyfied().setArray(i, x);
	}

	public void setByte(int parameterIndex, byte x) throws SQLException {
		argTraceSet(parameterIndex, Byte.toString(x));
		getProxyfied().setByte(parameterIndex, x);
	}

	/**
	 * @deprecated
	 */
	public void setUnicodeStream(int parameterIndex, InputStream x, int length)
			throws SQLException {
		argTraceSet(parameterIndex, "<Unicode InputStream of length " + length
				+ ">");
		getProxyfied().setUnicodeStream(parameterIndex, x, length);
	}

	public void setShort(int parameterIndex, short x) throws SQLException {
		argTraceSet(parameterIndex, Short.toString(x));
		getProxyfied().setShort(parameterIndex, x);
	}

	public boolean execute() throws SQLException {
		reportExecute(dumpedSql());
		return getProxyfied().execute();
	}

	public void setInt(int parameterIndex, int x) throws SQLException {
		argTraceSet(parameterIndex, Integer.toString(x));
		getProxyfied().setInt(parameterIndex, x);
	}

	public void setLong(int parameterIndex, long x) throws SQLException {
		argTraceSet(parameterIndex, Long.toString(x));
		getProxyfied().setLong(parameterIndex, x);
	}

	public void setFloat(int parameterIndex, float x) throws SQLException {
		argTraceSet(parameterIndex, Float.toString(x));
		getProxyfied().setFloat(parameterIndex, x);
	}

	public void setDouble(int parameterIndex, double x) throws SQLException {
		argTraceSet(parameterIndex, Double.toString(x));
		getProxyfied().setDouble(parameterIndex, x);

	}

	public void setBigDecimal(int parameterIndex, BigDecimal x)
			throws SQLException {
		argTraceSet(parameterIndex, x);
		getProxyfied().setBigDecimal(parameterIndex, x);

	}

	public void setURL(int parameterIndex, URL x) throws SQLException {

		argTraceSet(parameterIndex, x);
		getProxyfied().setURL(parameterIndex, x);

	}

	public void setString(int parameterIndex, String x) throws SQLException {

		argTraceSet(parameterIndex, x);

		getProxyfied().setString(parameterIndex, x);

	}

	public void setBytes(int parameterIndex, byte[] x) throws SQLException {
		argTraceSet(parameterIndex, "<byte[]>");
		getProxyfied().setBytes(parameterIndex, x);

	}

	public void setDate(int parameterIndex, Date x) throws SQLException {
		argTraceSet(parameterIndex, x);
		getProxyfied().setDate(parameterIndex, x);

	}

	public ParameterMetaData getParameterMetaData() throws SQLException {
		return getProxyfied().getParameterMetaData();
	}

	public void setDate(int parameterIndex, Date x, Calendar cal)
			throws SQLException {
		argTraceSet(parameterIndex, x);

		getProxyfied().setDate(parameterIndex, x, cal);

	}

	public ResultSet executeQuery() throws SQLException {
		reportQuery(dumpedSql());
		return getProxyfied().executeQuery();
	}


	public void setObject(int parameterIndex, Object x, int targetSqlType,
			int scale) throws SQLException {
		argTraceSet(parameterIndex, x);
		realPreparedStatement
				.setObject(parameterIndex, x, targetSqlType, scale);

	}

	public void setObject(int parameterIndex, Object x, int targetSqlType)
			throws SQLException {
		argTraceSet(parameterIndex,  x);
		getProxyfied().setObject(parameterIndex, x, targetSqlType);

	}

	public void setObject(int parameterIndex, Object x) throws SQLException {
		argTraceSet(parameterIndex, x);
		getProxyfied().setObject(parameterIndex, x);

	}

	public void setTimestamp(int parameterIndex, Timestamp x)
			throws SQLException {
		argTraceSet(parameterIndex, x);
		getProxyfied().setTimestamp(parameterIndex, x);
	}

	public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal)
			throws SQLException {
		argTraceSet(parameterIndex, x);
		getProxyfied().setTimestamp(parameterIndex, x, cal);

	}

	public int executeUpdate() throws SQLException {
		reportUpdate(dumpedSql());
		return getProxyfied().executeUpdate();

	}

	public void setAsciiStream(int parameterIndex, InputStream x, int length)
			throws SQLException {
		argTraceSet(parameterIndex, "<Ascii InputStream of length " + x + ">");

		getProxyfied().setAsciiStream(parameterIndex, x, length);

	}

	public void setBinaryStream(int parameterIndex, InputStream x, int length)
			throws SQLException {

		argTraceSet(parameterIndex, "<Binary InputStream of length " + length
				+ ">");

		getProxyfied().setBinaryStream(parameterIndex, x, length);

	}

	public void clearParameters() throws SQLException {
		synchronized (argTrace) {
			argTrace.clear();
		}
		getProxyfied().clearParameters();

	}

	public ResultSetMetaData getMetaData() throws SQLException {
		return getProxyfied().getMetaData();
	}

	public void addBatch() throws SQLException {
		_addInBatchContext(dumpedSql());
		getProxyfied().addBatch();
	}
}
